import apiuser from './api/user.js';
const method = {};

//路由跳转
method.router = function (router) {
	if(router.type == 0){
		return
	}
	
	if(router.is_need_login == 1){				//是否需要登录访问
		let login_id = method.get_storage_sync('id')
		if(login_id =='' || login_id == null || login_id == 'null'){
			method.is_has_login('hasLogin')
			return false
		}
	}
	
	if(router.is_tb_atuh == 1){				//是否需要淘宝授权打开
		let user_info = method.get_storage_sync('user_info')
		if(user_info.tb_rid == '' || user_info.tb_rid ==null || user_info.tb_rid == 'null' ){
			apiuser.taobao_auth({id:user_info.id}).then(res =>{				//淘宝授权链接
				if(res.code == 1){
					console.log(res)
					if(res.data.rid == '' || res.data.rid == null || res.data.rid =='null'){
						method.tb_openh5url(res.data.url)
					}else{
						apiuser.get_user({id:user_info.id}).then(res =>{	//收取之后从新刷新本地存储
							if(res.code == 1){
								user_info = method.set_storage_sync('user_info',res.data)
							}
						}).catch(cateres =>{
							
						});
					}
				}
			}).catch(cateres =>{
				
			});
			return false;
		}
	}
		
	let str_params=''
	if(router.data != ''){
		let json_params = JSON.parse(router.data)
		str_params = formatJsonParams(json_params)
	}
	
	if(router.relationId == 1){	//是否需要拼接淘宝rid
		let user_info = method.get_storage_sync('user_info')
		if(str_params.indexOf('?') < 0){
			str_params = '?relationId='+user_info.tb_rid
		}else{
			str_params = '&relationId='+user_info.tb_rid
		}
	}
	if(router.type==1){					//打开app内部页面
		uni.navigateTo({
			url:router.url+str_params
		})
	}
	
	if(router.type==2 && router.path=='H5'){		//打开app web页面
		let h5url=''
		if(str_params != ''){
			h5url='../../pages/common/web'+str_params+'&url='+router.url+"&title="+router.title
		}else{
			h5url='../../pages/common/web?url='+router.url+"&title="+router.title
		}
		uni.navigateTo({
			url:h5url
		})
	}
	
	if(router.type==3 && router.path=='AwakeTbApp'){		//打开淘宝app
		let tb_url = router.url+str_params
		method.tb_openurl(tb_url)
	}
	
	if(router.type==3 && router.path=='AwakePdd'){			//打开拼多多app
		plus.runtime.openURL(router.url)
	}
	
};


//打开一个web界面
method.weburl = function(url,title){
	uni.navigateTo({
		url:'../../pages/common/web?url='+url+"&title="+title
	})
};

/**
 * 百川初始化
 */
method.tb_init = function (){
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.init(
		result => {
			if(result.status){
				uni.showToast({
					title: "初始化成功"
				});
			}else{
				uni.showToast({
					title: "初始化失败"
				});
			}
			console.log(JSON.stringify(result))
		}
	)
};

method.tb_login = function() { //授权登录
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.login(
		result => {
			if(result.status){
				uni.showToast({
					title: "授权登陆成功"
				});
			}
			console.log(JSON.stringify(result))
		}
	)
};


method.tb_logout = function() {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.logout(
		result => {
		if(result.status){
			uni.showToast({
				title: "登出成功"
			});
		}	
			console.log(JSON.stringify(result))
		}
	)
};


/**
 * 打开一个淘宝的优惠券链接
 */
method.tb_openurl = function(tb_url,rid) {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	var url =tb_url;
	Alibcsdk.openurl({
		url: url,
		linkkey: "taobao",
		adzoneid: rid,
		pid: "mm_115184870_1673500165_110380900420",
		nativeFailedMode: "download",
		appkey: "29517930",
		opentype: 'native'
	}, result => {

	})
};




/**
渠道备案可以使用通用的渠道备案链接（可在淘宝联盟后台获取）后面拼接上rtag参数，改参数为自定义参数，可以为用户ID，用户通过该页面备案成功后
可通过taobao.tbk.sc.publisher.info.get( 淘宝客-公用-私域用户备案信息查询 )这个接口来获取对应rtag的渠道ID。页面地址：
https://open.taobao.com/api.htm?docId=37989&docType=2&scopeId=14474
*/
method.tb_openqdurl = function(tb_url) {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	var url = tb_url;
	Alibcsdk.openurl({
		url: url,
	}, result => {

	})
};



/*
申请渠道可以使用该方法打开H5授权登录页面，从服务端获取到access_token在调用渠道备案接口。
H5授权登录换取access_token见淘宝联盟开发平台，页面地址：https://open.taobao.com/doc.htm?docId=118&docType=1&spm=a219a.7395903.0.0.16af3971ApSa3N
https://oauth.m.taobao.com/authorize?response_type=code&client_id=你的appkey&redirect_uri=你的回调地址&state=自定义参数&view=web
*/
method.tb_openh5url = function(tb_auth_url) {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	let url = tb_auth_url
	Alibcsdk.openurl({
		url: url,
	}, result => {
		console.log(result)
		return result
	})
};





//打开商品详情
method.tb_opendetail=function(goods_id,rid) {
	console.log(goods_id)
	console.log(rid)
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.opendetail({
		itemid: goods_id,
		linkkey: "taobao",
		adzoneid: rid,
		pid: "mm_115184870_1673500165_110380900420",
		nativeFailedMode: "download",
		appkey: "29517930",
		opentype: 'native'
	}, result => {

	})
};



//打开店铺
method.tb_openshop = function(goods_shop_id,rid) {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.openshop({
		shopid: '57630185',
		sellerid: '202224264',
		linkkey: "taobao",
		adzoneid: rid,
		pid: "mm_115184870_1673500165_110380900420",
		nativeFailedMode: "download",
		appkey: "29517930",
		opentype: 'native'
	}, result => {

	})
};



/**
 * 打开我的购物车
 */
method.tb_openmycart = function(rid) {
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.openmycart({
		linkkey: "taobao",
		adzoneid: rid,
		pid: "mm_115184870_1673500165_110380900420",
		nativeFailedMode: "download",
		appkey: "29517930",
		opentype: 'native'
	}, result => {

	})
};


/**
 * 获取淘宝个人信息
 */
method.tb_getuserinfo = function(){
	let Alibcsdk = uni.requireNativePlugin('UZK-Alibcsdk');
	Alibcsdk.getuserinfo(
		result => {
			if(result.status){
				uni.showToast({
					title: "获取数据成功"
				});
			}else{
				uni.showToast({
					title: "未登陆"
				});
			}
			console.log(JSON.stringify(result))
		}
	)
};



/**
 * 封装数据本地存储
 */
method.set_storage_sync = function(key,value){
	try {
	    uni.setStorageSync(key,value);
	} catch (e) {
	    console.log('数据存储失败')
	}
}

/**
 * 获取本地数据
 */
method.get_storage_sync = function(key){
	try {
	    let value = uni.getStorageSync(key);
		return value
	} catch (e) {
	    console.log('缓存出错')
	}
}


/**
 * 下载网络图片到本地存储
 */
method.downloadfileimg = function(imgs){
	if(typeof(imgs) == 'string'){
		uni.downloadFile({
			url: imgs,
			success: (res) =>{
				if (res.statusCode === 200){
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function() {
							uni.showToast({
								title: "保存成功",
								icon: "none"
							});
						},
						fail: function() {
							uni.showToast({
								title: "保存失败，请稍后重试",
								icon: "none"
							});
						}
					});
				}
			}
		})
	}else{
		for(let i=0;i<imgs.length;i++){
			uni.downloadFile({
				url: imgs[i],
				success: (res) =>{
					if (res.statusCode === 200){
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function() {
							},
							fail: function() {
							}
						});
					}
				}
			})
		}
		uni.showToast({
			title: "保存成功",
			icon: "none"
		});
	}
}


/**
 * 更新用户信息
 */
method.update_set_user = function(){
	let user_info = method.get_storage_sync('user_info')
	apiuser.get_user({id:user_info.id}).then(res =>{	//收取之后从新刷新本地存储
		if(res.code == 1){
			user_info = method.set_storage_sync('user_info',res.data)
		}
	}).catch(cateres =>{
		
	});
}

/**
 * 时间戳时间格式转换
 */
 method.dateFormat = function(timestamp, formats) {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d'
    let zero = function (value) {
        if (value < 10) {
            return '0' + value
        }
        return value
    }
    let myDate = timestamp? new Date(timestamp): new Date()
    let year = myDate.getFullYear()
    let month = zero(myDate.getMonth() + 1)
    let day = zero(myDate.getDate())
    let hour = zero(myDate.getHours())
    let minite = zero(myDate.getMinutes())
    let second = zero(myDate.getSeconds())
    return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches]
    })
},



/**
 * 删除本地所有缓存
 */
method.clearStorage = function(){
	uni.clearStorage()
}

/**
 * 根据登录状态跳转登录界面
 */
method.is_has_login = function(haslogin){
	let haslogin_status = method.get_storage_sync(haslogin)
	if(!haslogin_status){
		uni.navigateTo({
			url: '../public/login',
			success: res => {},
			fail: () => {},
			complete: () => {}
		});
	}
}

/**
 * 判断用户是否安装了某款app
 */
method.is_user_appexsit = function(appname){
	switch(appname){
		case 'taobao':
			if(plus.runtime.isApplicationExist({  
				pname: 'com.taobao.taobao',  
				action: 'taobao://'  
			})){  
				return true
			}else{  
				return false
			}
		break
		
		case 'pdd':
			if(plus.runtime.isApplicationExist({  
				pname: 'com.xunmeng.pinduoduo',  
				action: 'pinduoduo://'  
			})){  
				return true
			}else{  
				return false
			}
		break
		
		case 'jd':
			if(plus.runtime.isApplicationExist({  
				pname: 'com.jingdong.app.mall',  
				action: 'openApp.jdMobile://'  
			})){  
				return true
			}else{  
				return false
			}
		break
	}
	return false
}



method.is_has_login = function(haslogin){
	let haslogin_status = method.get_storage_sync(haslogin)
	if(!haslogin_status){
		uni.navigateTo({
			url: '../public/login',
			success: res => {},
			fail: () => {},
			complete: () => {}
		});
	}
}

/**
 * 拼接对象为请求字符串
 * 对于需要编码的文本（比如说中文）我们要进行编码
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 **/
function formatJsonParams(obj) {
	const params = [];
	Object.keys(obj).forEach((key) => {
    let value = obj[key];
    if (typeof value !== 'undefined' || value !== null) {
      params.push([key, encodeURIComponent(value)].join('='));
    }
  })
  return '?' + params.join('&');
};

export default method